/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AirLine;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.util.*;
import Model.Model;
import Model.*;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrator
 */
public class CitySelect extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        String cityFrom = request.getParameter("cityFrom");
        String cityTo = request.getParameter("cityTo");

        int year = Integer.valueOf(request.getParameter("year"));
        int month = Integer.valueOf(request.getParameter("month"));
        int day = Integer.valueOf(request.getParameter("day"));
        Timestamp date1 = new Timestamp(((year - 1970) * 31556926 + (month * 2629743) + day * 86400) * 1000);
        int number = Integer.valueOf(request.getParameter("number"));
        int sortingOrder = Integer.valueOf(request.getParameter("sortingOrder"));
        System.err.println("from: " + cityFrom);


        HttpSession session = request.getSession();
        Model model = (Model) session.getAttribute("model");
        session.setAttribute("number", number);
        Airport from = null;
        Airport to = null;

        
        // get info from checkbox
        String airlines[] = request.getParameterValues("airlines");
        ArrayList<String> airlineList = new ArrayList<String>();
        
        for( String t : airlines )
            airlineList.add(t);

        
        
        TripHandler th = new TripHandler(from, to, number, sortingOrder, date1, model.getAirports(), model.getFlights(), airlineList);

        to = model.getAirPortByCode(cityTo);
        from = model.getAirPortByCode(cityFrom);



        System.out.println(from);


        TreeSet<Trip> trips = new TreeSet<Trip>();
        
        try{

        trips = th.getTrips();


        }catch(SQLException e){
            model.log(e.getMessage());
        }
        if( trips.isEmpty()) {
            // if there is no trips for input selection
            RequestDispatcher view =
                    request.getRequestDispatcher("result2.jsp");
                    view.forward( request, response );
        }
        else {
            session.setAttribute("trips", trips);
            RequestDispatcher view =
                    request.getRequestDispatcher("result.jsp");
            view.forward(request, response);
        }
        Iterator<Trip> it2 = trips.iterator();
        while (it2.hasNext()) {
            System.out.print(it2.next().getDepartureAirport());
        }
        System.out.print(trips.size());


    }
}
